package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private UserShopMapper userShopMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况处理(收获地址为null 超出配送范围 购物车 数据为空)
        AddressBook addressBook = addressMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查用户收货地址是否超出配送范围
//        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        //查询购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = userShopMapper.list(shoppingCart);
        //判断购物车是否为null
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //组装订单数据
        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //数据插入
        //向订单表插入1条数据
        orderMapper.insert(order);
        log.info("订单主键id:{}=======================>", order.getId());

        //插入订单详情表
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        //遍历购物车中的菜品或套餐,将菜品或套餐详情添加到详情表中
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);//拷贝基本信息
            //插入订单id
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);

        }
        orderDetailMapper.insert(orderDetails);

        //清空购物车
        userShopMapper.deleteByUserId(BaseContext.getCurrentId());

        //封装返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(order.getId());
        orderSubmitVO.setOrderNumber(order.getNumber());
        orderSubmitVO.setOrderAmount(order.getAmount());
        orderSubmitVO.setOrderTime(order.getOrderTime());

        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        Orders order = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), BaseContext.getCurrentId());
        order.setId(order.getId());
        order.setStatus(Orders.TO_BE_CONFIRMED);//订单状态,待接单
        order.setPayStatus(Orders.PAID);//支付状态
        order.setCheckoutTime(LocalDateTime.now());//支付时间
        orderMapper.update(order);//更行订单状态

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", order.getId());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单
     *
     * @param page     页码
     * @param pageSize 显示条数
     * @param status   状态
     * @return 返回pageResult
     */
    @Override
    public PageResult historyOrders(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        //查询用户订单,根据用户订单状态,查询用户订单详情
        //封装查询用户订单条件
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setPage(page);
        ordersPageQueryDTO.setPageSize(pageSize);
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        //分页查询用户订单
        Page<Orders> orders = orderMapper.selectQueryPage(ordersPageQueryDTO);

        //封装响应数据的集合
        ArrayList<OrderVO> orderDetails = new ArrayList<>();

        //遍历订单为每个订单封装响应数据
        for (Orders order : orders) {
            //查询用户订单详情
            List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(order.getId());
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            orderDetails.add(orderVO);
        }

        PageResult pageResult = new PageResult(orders.getTotal(), orderDetails);

        return pageResult;
    }

    /**
     * 查询订单详情
     *
     * @param orderId 订单id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long orderId) {
        //根据订单id查询订单信息
        Orders order = orderMapper.selectByOrderId(orderId);
        //根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(order.getId());
        //封装返回数据
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);//拷贝订单信息
        orderVO.setOrderDetailList(orderDetailList);//设置订单详情信息
        return orderVO;
    }

    /**
     * 用户取消订单
     *
     * @param orderId 用户订单id
     */
    @Override
    public void userCancelOrder(Long orderId) {
        //查询用户订单
        Orders orders = orderMapper.selectByOrderId(orderId);
        //对不能取消订单的情况抛出异常
        //订单为空
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单不为待付款或待接单状态
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //对已接单的订单做退款操作
        if (orders.getStatus() == 3) {
            //调用微信接口退款
            //修改支付状态
            orders.setPayStatus(Orders.REFUND);
        }

        //修改订单状态、取消原因、取消时间
        orders.setStatus(6);
        orders.setRejectionReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param orderId
     */
    @Override
    public void repetition(Long orderId) {
        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orderId);

        //将订单详情转为购物车对象,插入到购物车中
        for (OrderDetail orderDetail : orderDetailList) {
            //处理为购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            userShopMapper.insert(shoppingCart);
        }
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO 搜索条件DTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页查询所有订单
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.selectQueryPage(ordersPageQueryDTO);

        //将订单转为ListOrderVo返回
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        for (Orders order : orders) {
            //封装订单基本信息
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);

            //遍历每一个订单详情,封装订单详情信息返回处理后的字符串
            List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(order.getId());
            //拼接订单菜品信息字符串
            List<String> orderDetailString = orderDetailList.stream().map(orderDetail -> {
                String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
                return orderDish;
            }).collect(Collectors.toList());
            //封装订单菜品信息字符串
            orderVO.setOrderDishes(String.join("<===>", orderDetailString));

            //添加到ListOrderVo集合中返回
            orderVOS.add(orderVO);
        }

        //返回订单数量,订单信息+订单菜品信息拼接后的字符串
        PageResult pageResult = new PageResult(orders.getTotal(), orderVOS);

        return pageResult;
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistic() {
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);//待接单
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);//待派送
        Integer deliverInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);//派送中

        //封装返回对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliverInProgress);

        return orderStatisticsVO;
    }

    /**
     * 商家接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());//订单id
        orders.setStatus(Orders.CONFIRMED);//修改为已接单状态
        orderMapper.update(orders);
    }

    /**
     * 商家拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //查询订单
        Orders order = orderMapper.selectByOrderId(ordersRejectionDTO.getId());
        //对订单不存在或订单不是待接单状态抛出异常
        if (order == null || !(order.getStatus().equals(Orders.TO_BE_CONFIRMED))) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //对已支付订单为用户退款操作
        if (order.getPayStatus().equals(Orders.PAID)) {
            //调用微信支付接口退款操作 TODO
            //修改支付状态为取消状态
            order.setPayStatus(2);
            log.info("退款成功=======>");
        }

        //修改订单状态为拒单状态
        //设置订单id
        order.setId(ordersRejectionDTO.getId());
        //订单取消时间
        order.setCancelTime(LocalDateTime.now());
        //订单取消原因
        order.setCancelReason(ordersRejectionDTO.getRejectionReason());
        //设置订单取消状态
        order.setStatus(Orders.CANCELLED);

        orderMapper.update(order);
    }

    /**
     * 商家取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders order = orderMapper.selectByOrderId(ordersCancelDTO.getId());
        //对已支付订单做退款操作
        if (order.getPayStatus().equals(Orders.PAID)) {
            //调用微信支付接口退款操作 TODO
            //修改支付状态
            order.setPayStatus(Orders.REFUND);
        }

        //修改订单状态
        //设置订单id
        order.setId(ordersCancelDTO.getId());
        //订单取消时间
        order.setCancelTime(LocalDateTime.now());
        //订单取消原因
        order.setCancelReason(ordersCancelDTO.getCancelReason());
        //设置订单取消状态
        order.setStatus(Orders.CANCELLED);

        orderMapper.update(order);
    }

    /**
     * 商家派送订单
     *
     * @param orderId 订单id
     */
    @Override
    public void delivery(Long orderId) {
        //查询订单
        Orders order = orderMapper.selectByOrderId(orderId);

        //对订单为null或不是已接单订单抛出异常
        if (order == null || !(order.getStatus().equals(Orders.CONFIRMED))) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        //设置订单id
        order.setId(orderId);
        //设置订单状态为派送中
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(order);
    }

    /**
     * 商家完成订单
     *
     * @param orderId 订单id
     */
    @Override
    public void complete(Long orderId) {
        //查询订单
        Orders order = orderMapper.selectByOrderId(orderId);

        //对订单为null或不是派送中订单抛出异常
        if (order == null || !(order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS))) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        //设置订单id
        order.setId(orderId);
        //设置订单状态为已完成状态
        order.setStatus(Orders.COMPLETED);
        //设置订单送达时间
        order.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(order);
    }

    /**
     * 客户催单
     * @param orderId
     */
    @Override
    public void reminder(Long orderId) {
        //判断订单是否存在
        Orders order = orderMapper.selectByOrderId(orderId);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //服务端使用socket向客户端发送催单
        Map map = new HashMap();
        map.put("type", 2);//消息类型，1表示催单提醒
        map.put("orderId", order.getId());
        map.put("content", "订单号：" + order.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
